#ifndef __SOFTWAREIIC_H__
#define __SOFTWAREIIC_H__

#include "plat/stream.h"
#include "soc/soc_gpio.h"


/// @brief 
class SoftWareIIC : public Stream
{
public:
    explicit SoftWareIIC();
    explicit SoftWareIIC(const GpioPortPin &portSCL, const GpioPortPin &portSDA);
    virtual ~SoftWareIIC();

public:
    void Config(const GpioPortPin &sclPortPin, const GpioPortPin &sdaPortPin);
    void SetClkDelay(int us);

    bool Write(uint8_t addr, uint8_t reg, uint8_t *buffer, int len);
    bool Read(uint8_t addr, uint8_t reg, uint8_t *buffer, int len);

    bool WriteByte(uint8_t addr, uint8_t reg, uint8_t val);
    bool ReadByte(uint8_t addr, uint8_t reg, uint8_t &val);

public:
    int available(){return 1;}
    int read();
    size_t write(uint8_t c);
    
private:
    void StartSignal();
    void StopSignal();
    bool WaitAckSignal();
    void AckSignal();
    void NAckSignal();
    
    bool SendByte(uint8_t dat);
    uint8_t ReceiveByte(bool ack);

private:
    GpioPortPin m_SCLPortPin;
    GpioPortPin m_SDAPortPin;
    int m_clkDelay = 1; //us
};

#endif // __SOFTWAREIIC_H__
